<!--
 * @Author: 小花
 * @Date: 2022-03-04 16:34:26
 * @LastEditors: 小花
 * @LastEditTime: 2022-05-20 10:42:37
 * @Description: 
-->
<template>
  <el-collapse v-model="historyAnnouncement">
    <el-collapse-item name="1">
      <template #title>
        <i class="fa fa-bullhorn" aria-hidden="true"></i>&nbsp;公告
      </template>
      <el-alert v-for="item in pageAnnouncementList" :key="item.id" :title="item.title"
        :type="item.alertType || 'info'" :closable="false">
        <div class="layout">
          <div class="content">{{ item.content }}</div>
          <div class="about">
            <div class="issueAuthor">
              <i class="fa fa-user-circle-o"></i>&nbsp;{{ item.issueAuthor }}
            </div>
            <div class="issueTime">
              <span><i class="fa fa-clock-o"
                  aria-hidden="true"></i>&nbsp;{{ item.issueTime }}</span>
            </div>
          </div>
        </div>
      </el-alert>
      <div class="pagination">
        <el-pagination @size-change="val => pagination.pageSize = val"
          @current-change="val => pagination.currentPage = val"
          :current-page="pagination.currentPage" :pager-count="pagination.pagerCount"
          :page-sizes="pagination.pageSizes" :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" background>
        </el-pagination>
      </div>
    </el-collapse-item>
  </el-collapse>
  <div class='repairCenter_container'>
    <el-card class="box-card">

      <div slot="header" class="clearfix">
        <span>申请报修</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="onSubmit">提交申请
        </el-button>
      </div>

      <el-form :model="orderForm" modelValue :rules="rules" status-icon label-width="8rem"
        ref="ruleForm">
        <el-form-item label="联系地址" prop="repairAddress">
          <el-input v-model="orderForm.repairAddress" clearable></el-input>
        </el-form-item>

        <el-form-item label="手机号码" prop="repairPhone">
          <el-input v-model="orderForm.repairPhone" clearable maxlength="11" minlength="11">
          </el-input>
        </el-form-item>

        <el-form-item label="报修类型" prop="typeMark">
          <el-badge value="hot" class="item repairTypeStyle" v-for="item in repairType"
            :key="item.mark" :hidden="!item.typeHot">
            <el-tag class="" @click="tagEvent(item)" :type="item.tagType">
              {{item.typeValue}}
            </el-tag>
          </el-badge>
        </el-form-item>

        <el-form-item label="报修问题" prop="repairContent">
          <el-input type="textarea" clearable v-model="orderForm.repairContent" show-word-limit>
          </el-input>
        </el-form-item>

        <el-form-item label="图片资料">
          <el-upload class="avatar-uploader" :action="action" list-type="picture-card" ref="upload"
            multiple :auto-upload="false" :http-request="uploadFile"
            accept=".jpg,.jpeg,.png,.JPG,.JPEG" :on-preview="handlePictureCardPreview"
            :on-remove="(file, fileList)=>{return handleRemove(file, fileList)}" :limit="3"
            :on-exceed="onExceed"
            :on-success="(response, file, fileList)=>{return onSuccess(response, file, fileList)}">
            <i class="fa fa-plus" aria-hidden="true"></i>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    //这里存放数据
    return {
      historyAnnouncement: '1',
      announcementList: [],
      pagination: {
        pageSize: 3,
        pageSizes: [3, 10, 100, 200],
        pagerCount: 5,
        currentPage: 1,
        total: 0
      },
      repairType: [],
      orderForm: {
        typeMark: '',
        repairAddress: '3423',
        repairContent: '厕所喷屎',
        repairPhone: '15281056531'
      },
      rules: {
        typeMark: [
          { required: true, message: '请选择报修类型', trigger: 'change' },
        ],
        repairAddress: [
          { required: true, message: '请输入联系地址', trigger: 'blur' },
        ],
        repairPhone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        repairContent: [
          { required: true, message: '请输入报修问题', trigger: 'blur' },
        ]
      },
      action: this.axios.defaults.baseURL + "/userHome/photo",
      formData: '',
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false
    }
  },
  //监听属性 类似于data概念
  computed: {
    'pageAnnouncementList': function () {
      return this.announcementList.slice(
        (this.pagination.currentPage - 1) * this.pagination.pageSize, this.pagination.currentPage * this.pagination.pageSize
      )
    },
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    /**
     * @description: 后端拉取所有公告信息
     * @param {*}
     * @return {*}
     */
    async execPullAllAnnouncement () {
      const result = await (await this.axios.get('/userHome/pullAllAnnouncement')).data
      if (result.code === 43000) {
        this.announcementList = result.data || []
        this.announcementList.sort(function (a, b) {
          return b.issueTime < a.issueTime ? -1 : 1
        })
        this.pagination.total = this.announcementList.length
      } else if (result.code === 43001) {
        ElMessage.warning(result.msg)
      }
    },
    tagEvent (item) {
      if (item.tagType == 'info') {
        //此处修改选中报修类型样式
        item.tagType = 'danger';
        this.orderForm.typeMark = item.typeMark;
      } else {
        item.tagType = 'info';
        this.orderForm.typeMark = '';
      }
      this.repairType.forEach((it, index) => {
        if (item.typeMark != it.typeMark) {
          it['tagType'] = 'info'
        }
      })
      this.$forceUpdate();
    },
    getRepairType () {
      this.axios.get("/userHome/repairType").then(res => {
        if (res.data.code == 43000) {
          this.repairType = res.data.data
          this.repairType.forEach((item, index) => {
            item['tagType'] = 'info'
          })
        }
      });
    },
    /**
     * userHome/createOrder
     * orderForm:{"repairAddress":"3303","repairPhone":"17345252917","typeMark":1}
     * @description: 文件超出个数限制时的钩子
     * @param {*} files
     * @param {*} fileList
     * @return {*}
     * @author: 小花
     */
    onExceed (files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    /**
     * @description: 手动文件上传
     * @param {*}
     * @return {*}
     * @author: 小花
     */
    submitUpload () {
      this.formData = new FormData();
      this.formData.append('orderForm', JSON.stringify(this.orderForm));
      this.$refs.upload.submit();

      let i = this.formData.entries();
      if (i.next().done) return;

      let config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          'satoken': localStorage.getItem("satoken")
        }
      }
      this.axios.post("/userHome/createOrder", this.formData, config).then(res => {
        if (res.data.code == 43000) {
          this.$message.success("申请报修成功");
          this.$refs.upload.clearFiles();
          this.orderForm = {};
        }

      }).catch(res => {
        console.log(res)
      })
    },
    uploadFile (file) {
      this.formData.append('file', file.file);
    },
    /**
     * @description: 上传成功返回列表显示
     * @param {*} response
     * @param {*} file
     * @param {*} fileList
     * @param {*} idx
     * @return {*}
     * @author: 小花
     */
    onSuccess (response, file, fileList, idx) {
      // 这里是element的上传地址，对应的name,url,自己打印fileList对照
      this.formList.push({ name: file.name, url: file.url });
    },
    /**
     * @description: 移除图片
     * @param {*} file
     * @param {*} fileList
     * @param {*} idx
     * @return {*}
     * @author: 小花
     */
    handleRemove (file, fileList) { },
    /**
     * @description: 图片放大
     * @param {*} file
     * @return {*}
     * @author: 小花
     */
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    /**
     * @description: 提交申请报修
     * @param {*}
     * @return {*}
     * @author: 小花
     */
    onSubmit () {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          this.submitUpload();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.getRepairType();
    this.execPullAllAnnouncement()
  }
}
</script>

<style lang='scss' scoped>
//@import url(); 引入公共css类
.repairCenter_container {
  .repairTypeStyle {
    cursor: pointer;
    margin-top: 10px;
    margin-right: 40px;
  }
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
.el-collapse {
  user-select: none;
  .el-alert {
    margin-bottom: 1rem;
    :deep(.el-alert__content) {
      width: 100%;
      .layout {
        .about {
          text-align: right;
        }
      }
    }
  }
}
.pagination {
  display: flex;
  justify-content: center;
  margin-top: 1rem;
  align-items: center;
}
</style>